package top.chenyaohua.init.imp;

import com.alibaba.fastjson.JSON;
import com.google.auto.service.AutoService;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.chenyaohua.asm.CustomClassVisit;
import top.chenyaohua.asm.BeanMetadata;
import top.chenyaohua.context.BeanFactory;
import top.chenyaohua.init.abstractInit.AbstractInitExecution;
import top.chenyaohua.utils.InitExecutionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@AutoService(AbstractInitExecution.class)
public class RegisterInit extends AbstractInitExecution {

    private final static Logger LOGGER = LoggerFactory.getLogger(RegisterInit.class);


    public RegisterInit () {
        super(2);
    }



    @Override
    public boolean init () {
      //  new Thread(RegisterInit.this::register,"类信息获取线程").start();
        return register();
    }

    protected boolean register(){
        LOGGER.debug("开始扫描到的类信息");

        try {
            ArrayList<String> packages = null;
            List<BeanMetadata> beans = new ArrayList<>();
            ScanInit scanInit  = (ScanInit)InitExecutionUtils.get().get(this.order - 1);
            packages = scanInit.getPackages();

            for (String className : packages) {

                BeanMetadata beanMetadata = new BeanMetadata(className);
                ClassReader cr = new ClassReader(className);
                ClassWriter cw = new ClassWriter(cr,ClassWriter.COMPUTE_FRAMES);
                CustomClassVisit ccv = new CustomClassVisit(cw,beanMetadata);

                cr.accept(ccv,ClassReader.EXPAND_FRAMES);

                LOGGER.debug("扫描到的类信息 beanMetadata={}", JSON.toJSONString(beanMetadata));

                beans.add(beanMetadata);
            }
            BeanFactory.setBeanMetadata(beans);
            BeanFactory.register();
            return true;
        } catch (IOException e) {
            LOGGER.error("扫描类信息异常:",e);
            return false;
        }
    }
}
